package com.gxitsky.socket;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author gxing
 * @desc TODO
 * @date 2022/2/12
 */
@Service
public class SocketServiceImpl implements SocketService {

    public void socketServer() {
        try {
            ServerSocketChannel serverChannel = ServerSocketChannel.open();
            Selector selector = Selector.open();
            serverChannel.configureBlocking(false);
            serverChannel.register(selector, SelectionKey.OP_READ);
            while (true) {
                int readyChannels = selector.select();
                if (readyChannels == 0) {
                    continue;
                }
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        // 可接收连接
                    } else if (key.isConnectable()) {
                        // 连接就绪
                    } else if (key.isReadable()) {
                        // 读就绪
                    } else if (key.isWritable()) {
                        // 写就绪
                    }
                    iterator.remove();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
